﻿using System.Threading.Tasks;
using AspnetIdentity.Data.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace AspnetIdentity.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signinManager;

        public LoginController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signinManager)
        {
            _userManager = userManager;
            _signinManager = signinManager;
        }

        [HttpPost("Register")]
        public async Task<IdentityResult> Register([FromBody]LoginViewModel model)
        {
            var identityUser = new ApplicationUser
            {
                UserName = model.UserName,
                PasswordHash = model.PassWorld,
                NormalizedEmail = model.UserName
            };

            return await _userManager.CreateAsync(identityUser, model.PassWorld);
        }

        [HttpPost("Login")]
        public async Task<Microsoft.AspNetCore.Identity.SignInResult> LoginAsync([FromBody]LoginViewModel model)
        {
            var identityUser = new ApplicationUser
            {
                UserName = model.UserName,
                PasswordHash = model.PassWorld,
                NormalizedEmail = model.UserName
            };
            var user = await _userManager.FindByNameAsync(model.UserName);
            //var success = await _userManager.CheckPasswordAsync(user, identityUser.PasswordHash);
            //if (success)
            //{

            //}

            var siginresult = await _signinManager.PasswordSignInAsync(user, model.PassWorld, true, true);

            return siginresult;
        }
    }
}